package com.atguigu.survey.component.handler.guest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.atguigu.survey.component.service.i.UserService;
import com.atguigu.survey.e.UserNameAlreadyExistsException;
import com.atguigu.survey.entities.guest.User;
import com.atguigu.survey.utils.DataProcessUtils;
import com.atguigu.survey.utils.GlobalSettings;

@Controller
public class UserHandler {
    @Autowired
    private UserService userService;

    @RequestMapping("/guest/user/regist")
    public String regist(User user) throws Exception {
        // 1.验证用户名是否存在，如果存在，给予提示
        String userName = user.getUserName();
        String userPwd = user.getUserPwd();
        boolean exists = userService.existsUserName(userName);

        if (exists) {
            throw new UserNameAlreadyExistsException(GlobalSettings.MESSAGE_USERNAME_EXISTS);
        }

        // 2.密码加密
        String md5UserPwd = DataProcessUtils.md5(userPwd);
        user.setUserPwd(md5UserPwd);
        // 3.保存用户信息
        boolean flag = userService.regist(user);

        if (flag) {
            return "redirect:/index.jsp";
        }
        return "guest/user_regist";

    }
}
